import xmltodict
import re
import pickle

pl = pickle.load(open("pl.db",'rb'))
sd = pickle.load(open("sd.db",'rb'))
de = pickle.load(open("de.db",'rb'))

class MsgVerify:

    @staticmethod
    def clean(s):
        return re.sub(r'<([\u4e00-\u9fa5]+)>',r'{\1}',s)

    @staticmethod
    def restore(s):
        return re.sub(r'{([\u4e00-\u9fa5]+)}',r'<\1>',s)

class ShareMsgVerify(MsgVerify):
    
    @staticmethod
    def check(obj):
        #try:
        msg = MsgVerify.clean(obj["msg_body"])
        obj = xmltodict.parse(msg)
    
        #共享文档
        if "ClinicalDocument" in obj:
            msg_type = "SD"
            type_key = obj["ClinicalDocument"]["templateId"]["@root"]
            type_index, title = sd[type_key]
            name = obj["ClinicalDocument"]["recordTarget"]["patientRole"]["patient"]["name"]
            msg_body = MsgVerify.restore(msg)
            result = {"title": title, "name": name, "msg_type": msg_type, "type_index" : type_index, "msg_body": msg_body}
            return (True, result)
        elif "BasicDataset" in obj:
            msg_type = "DE"
            type_key = obj["BasicDataset"]["DataSet"]["@code"]
            type_index, title = de[type_key]
            msg_body = MsgVerify.restore(msg)
            result = {"title": title, "msg_type": msg_type, "type_index" : type_index, "msg_body": msg_body}
            return (True, result)
        return (False, {})

class RequestMsgVerify(MsgVerify):

    @staticmethod
    def check(obj):
        type_index = obj["type_index"]
        msg = MsgVerify.clean(obj["msg_body"])
        obj = xmltodict.parse(msg)

        #交互规范
        msg_type = "PL"
        try:
            title, allowed_templates = pl[type_index]
        except:
            print("illegal template")
            return (False, {})
        template = list(obj.keys())[0]
        if not template in allowed_templates:
            print("not allowed template: "+template)
            return (False, {})
        #所有的都是正向请求
        api_type = "T"
        msg_body = MsgVerify.restore(msg)
        result = {"title": title, "msg_type": msg_type, "type_index" : type_index, "msg_body": msg_body, "api_type": api_type}
        return (True, result)

